import _ from 'lodash'
import ebus from 'libs/ebus.js'
import {devmngApi} from '../../api.js'
import * as types from '../mutation-types'

//ddis dev
function makeDdisDev(ddisDev) {
  var port = 8080
  if ((ddisDev.devType === 'encoder')
    || (ddisDev.devType === 'decoder')) {
    port = 8080
  } else if (ddisDev.devType === 'server.media') {
    port = 6080
  } else {
    return
  }
  ddisDev.link = `<a href="http://${ddisDev.ipaddr}:${port}" target="_blank">Home</a>` 
}

export function doLoadDdisDevs({dispatch}) {
  dispatch(types.REFRESH_DDIS_DEVS_START)
  devmngApi.getItems('ddisDevs').then(function(res) {
    if (res && res.data && res.data.code === 0) {
      var ddisDevs = res.data.data.ddisDevs
      _.forEach(ddisDevs, (item, index) => {
        item._id = index + 1
        makeDdisDev(item)
      })
      dispatch(types.SET_DDIS_DEVS, ddisDevs)
    }
    dispatch(types.REFRESH_DDIS_DEVS_END)
  })
}

//topo summary
export function doLoadTopoSummary({dispatch, state}, {init = false, cb = {}} = {}) {
  if (init && state.devmng.topoSummary.init) {
    return
  }
  devmngApi.getItems('topoDevsSummary').then(function(res) {
    if (res && res.data && res.data.code === 0) {
      dispatch(types.SET_TOPO_SUMMARY, res.data.data.topoDevsSummary)
      cb && cb.success && cb.success()
    } else {
      cb && cb.error && cb.error(res.data)
    }
  }, function(res) {
    cb && cb.noResponse && cb.noResponse()
  })
}

//topo binds
export function doLoadTopoBinds({dispatch, state}, {init = false} = {}) {
  if (init && state.devmng.topoBinds.init) {
    return
  }
  devmngApi.getItems('topoBinds').then(function(res) {
    if (res && res.data && res.data.code === 0) {
      dispatch(types.SET_TOPO_BINDS, res.data.data.topoBinds)
    }
  })
}